﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using DaInterFace;
using DaInterFace.SYN;
using Newtonsoft.Json;

namespace DaFunction.SYN
{
    public class SYNSerial : ISYNSerial
    {
        public String Serializer(SerialType style, Type type, object obj)
        {
            string str = "";
            switch (style)
            {
                case SerialType.Json:
                    str = JsonConvert.SerializeObject(obj);
                    break;
                case SerialType.Xml:
                    MemoryStream Stream = new MemoryStream();
                    XmlSerializer xml = new XmlSerializer(type);
                    //序列化对象
                    xml.Serialize(Stream, obj);
                    Stream.Position = 0;
                    StreamReader sr = new StreamReader(Stream);
                    str = sr.ReadToEnd();

                    sr.Dispose();
                    Stream.Dispose();
                    break;
            }

            return str;
        }

        public object Deserialize(SerialType style, Type type, string strObj)
        {
            object obj = null;
            switch (style)
            {
                case SerialType.Json:
                    obj = JsonConvert.DeserializeObject(strObj, type);
                    break;
                case SerialType.Xml:
                    using (StringReader sr = new StringReader(strObj))
                    {
                        XmlSerializer xmldes = new XmlSerializer(type);
                        obj = xmldes.Deserialize(sr);
                    }
                    break;
            }

            return obj;
        }
    }
}
